{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 二叉树"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " 在实际使用时会根据链表和有序数组等数据结构的不同优势进行选择。有序数组的优势在于二分查找，链表的优势在于数据项的插入和数据项的删除。但是在有序数组中插入数据就会很慢，同样在链表中查找数据项效率就很低。综合以上情况，二叉树可以利用链表和有序数组的优势，同时可以合并有序数组和链表的优势，二叉树也是一种常用的数据结构。 "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 一般树结构\n",
    "\n",
    "<img src=\"image/chapter05/BinaryTree.jpeg\" width=500>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 二叉树结构\n",
    "\n",
    "<img src=\"image/chapter05/binarytree.png\" width=300>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 结点表示"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F\n",
      "H\n"
     ]
    }
   ],
   "source": [
    "class BinaryTree:\n",
    "    \n",
    "    # 定义一个根结点\n",
    "    def __init__(self,value,left=None,right=None):\n",
    "        self.root = value\n",
    "        self.left = left\n",
    "        self.right = right\n",
    "    \n",
    "    # 插入一颗左子树\n",
    "    def insertLeft(self,newNode):\n",
    "        # I. 当没有左子树时，直接插入\n",
    "        # II.如果有左子树，那么插入一个节点并将现有的子节点放在树的下一层\n",
    "        if self.left == None:\n",
    "            self.left = BinaryTree(newNode)\n",
    "        else:\n",
    "            t = BinaryTree(newNode)\n",
    "            t.left = self.left\n",
    "            self.left = t\n",
    "        return True\n",
    "    \n",
    "    # 插入一颗右子树\n",
    "    def inserRight(self,newNode):\n",
    "        if self.right == None:\n",
    "            self.right = BinaryTree(newNode)\n",
    "        else:\n",
    "            t = BinaryTree(newNode)\n",
    "            t.right = self.right\n",
    "            self.right = t\n",
    "        return True\n",
    "\n",
    "            \n",
    "if __name__ == \"__main__\":\n",
    "    example = BinaryTree('G',\n",
    "                         BinaryTree('D',\n",
    "                                    BinaryTree('A'),\n",
    "                                    BinaryTree('F',\n",
    "                                               BinaryTree('E'))),\n",
    "                         BinaryTree('M',\n",
    "                                    BinaryTree('H'),\n",
    "                                    BinaryTree('Z')))\n",
    "    print(example.left.right.root)\n",
    "    print(example.right.left.root)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 二叉树类型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 满二叉树"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 如果二叉树中所有分支结点的度数为2，则称它为一颗满二叉树。\n",
    "\n",
    "<img src=\"image/chapter05/man.jpg\" width=350>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 完全二叉树"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 对于一颗高度位h的二叉树，如果第0层至第h-1层的结点都满（也就是说每个结点的度都为2）。如果最下一层的结点不满，则所有结点在最左边连续排列，空位都在最右边。\n",
    "\n",
    "<img src=\"image/chapter05/wanquan.jpeg\" width=500>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 树的遍历"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们已经见到了树数据结构的基本功能,现在是看树的一些额外使用模式的时候了。这些使用模式可以分为我们访问树节点的三种方式。有三种常用的模式来访问树中的所有节点。这些模式之间的差异是每个节点被访问的顺序。\n",
    "\n",
    "$\\bullet$ 前序遍历 <br>\n",
    "$\\bullet$ 中序遍历 <br>\n",
    "$\\bullet$ 后序遍历 <br>\n",
    "\n",
    "<img src=\"image/chapter05/order.jpeg\" width=350>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 前序遍历"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 在前序遍历中,我们首先访问根节点,然后递归地做左侧子树的前序遍历,随后是右侧子树的递归前序遍历。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preorder:  GDAFEMHZ"
     ]
    }
   ],
   "source": [
    "def Preorder(tree):\n",
    "    if tree:\n",
    "        print(tree.root,end='')\n",
    "        Preorder(tree.left)\n",
    "        Preorder(tree.right)\n",
    "    return True\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    print(\"Preorder:  \",end='')\n",
    "    Preorder(example)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 中序遍历"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 在一个中序遍历中,我们递归地对左子树进行一次遍历,访问根节点,最后递归遍历右子树。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Inorder:  ADEFGHMZ"
     ]
    }
   ],
   "source": [
    "def Inorder(tree):\n",
    "    if tree:\n",
    "        Inorder(tree.left)\n",
    "        print(tree.root,end='')\n",
    "        Inorder(tree.right)\n",
    "    return True\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    print(\"Inorder:  \",end='')\n",
    "    Inorder(example)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 后序遍历"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 后序\t在后序遍历中,我们递归地对左子树和右子树进行后序遍历,然后访问根节点。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Postorder:  AEFDHZMG"
     ]
    }
   ],
   "source": [
    "def Postorder(tree):\n",
    "    if tree:\n",
    "        Postorder(tree.left)\n",
    "        Postorder(tree.right)\n",
    "        print(tree.root,end='')\n",
    "    return True\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    print(\"Postorder:  \",end='')\n",
    "    Postorder(example)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 节点个数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "TreeNodes = 8\n"
     ]
    }
   ],
   "source": [
    "def TreeNodes(tree):\n",
    "    if tree is None:\n",
    "        return 0\n",
    "    else:\n",
    "        return 1 + TreeNodes(tree.left) + TreeNodes(tree.right)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    print(\"TreeNodes = {}\".format(TreeNodes(example)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
